package com.rongxun.main.viewmodel;

import android.Manifest;
import android.app.Application;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;

import com.amap.api.location.AMapLocation;
import com.rongxun.api.AppSysInfoManager;
import com.rongxun.api.UserInfoManager;
import com.rongxun.api.config.Constants;
import com.rongxun.api.dao.response.Advertisement;
import com.rongxun.api.utils.FlyLog;
import com.rongxun.common.aroute.RouteUtil;
import com.rongxun.common.base.mvvm.event.SingleLiveEvent;
import com.rongxun.common.base.mvvm.viewmodel.BaseViewModel;
import com.rongxun.common.manager.ActivityManager;
import com.rongxun.common.utils.LocationUtils;
import com.rongxun.common.utils.MyToast;
import com.rongxun.common.utils.StringUtil;
import com.rongxun.common.widget.SimpleStyleDialog;
import com.rongxun.main.model.SplashModel;
import com.rongxun.main.ui.common.AdvertisementActivity;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import androidx.annotation.NonNull;
import io.reactivex.functions.Consumer;

/**
 * 创建者     forza
 * 创建时间   2019/11/29 18:09
 * 描述
 */
public class SplashViewModel extends BaseViewModel<SplashModel> implements LocationUtils.MyLocationListener {

    /**
     * 基本权限管理
     */
    private final String[] BASIC_PERMISSIONS = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
    };

    private final static String CHANNEL_ACTIVITY = "activity";
    private final static String CHANNEL_VIVO     = "vivo";


    private SingleLiveEvent<Class> mStartActivityEvent;


    public SplashViewModel(@NonNull Application application, SplashModel model) {

        super(application, model);

    }

    public SingleLiveEvent<Class> getStartActivityEvent() {

        if (mStartActivityEvent == null) {
            mStartActivityEvent = new SingleLiveEvent<>();
        }

        return mStartActivityEvent;
    }


    @Override
    public void onCreate() {

        super.onCreate();

        checkPermissions(BASIC_PERMISSIONS);
    }


    @Override
    protected void onCleared() {
        super.onCleared();
        LocationUtils.destroy();
    }

    @Override
    protected void getPermissionsSuccessful(String[] permissions) {

        String channel = AppSysInfoManager.getInstance().getChannel();

        switch (channel) {

            case CHANNEL_ACTIVITY:

                UserInfoManager.getInstance(getApplication().getApplicationContext()).setUIConfig(UserInfoManager.NEED_TRANSACTION);

                RouteUtil.forwardHome(getApplication().getApplicationContext());

                getUIChangeLiveData().getFinishActivityEvent().call();

                break;
            case CHANNEL_VIVO:

                LocationUtils.getLocation(this);

                break;

            default:

                getUIConfiguration();

        }

    }


    @Override
    public void result(AMapLocation location) {

        switch (location.getErrorCode()) {

            case LocationUtils.GET_LOCATION_SUCCESS:

                handleSuccessLocation(location);

                break;

            case LocationUtils.NO_LOCATION_PERMISSIONS:

                UserInfoManager.getInstance(getApplication().getApplicationContext()).setUIConfig(UserInfoManager.NO_TRANSACTION);

                RouteUtil.forwardHome(getApplication().getApplicationContext());

                getUIChangeLiveData().getFinishActivityEvent().call();

                break;

            default:

                getUIConfiguration();

        }

    }

    private String[] locations = {"深圳市", "北京市", "杭州市", "南京市"};

    private void handleSuccessLocation(AMapLocation location) {

        String city = location.getCity();

        FlyLog.d("city:" + city);

        if (StringUtil.isEmpty(city) || Arrays.asList(locations).contains(city)) {

            UserInfoManager.getInstance(getApplication().getApplicationContext()).setUIConfig(UserInfoManager.NO_TRANSACTION);

            RouteUtil.forwardHome(getApplication().getApplicationContext());

            getUIChangeLiveData().getFinishActivityEvent().call();

        } else {

            getUIConfiguration();

        }
    }


    private void getUIConfiguration() {
        addSubscribe(getModel().getUIConfiguration().subscribe(new Consumer<Advertisement>() {
            @Override
            public void accept(Advertisement advertisement) {
                handleAdvertising(advertisement);
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) {

                handleAdvertising(null);

            }
        }));
    }

    private void handleAdvertising(Advertisement advertising) {

        if (advertising != null && !StringUtil.isEmpty(advertising.getImgUrl())) {

            new CountDownTimer(400, 100) {
                @Override
                public void onTick(long finish) {
                }

                @Override
                public void onFinish() {
                    Map<String, Object> map = new HashMap<>();

                    Bundle bundle = new Bundle();
                    bundle.putSerializable(Constants.ActivityExtra.ENTITY, advertising);

                    map.put(ParameterField.CLASS, AdvertisementActivity.class);

                    map.put(ParameterField.BUNDLE, bundle);

                    getUIChangeLiveData().getStartActivityEvent().postValue(map);

                    getUIChangeLiveData().getFinishActivityEvent().call();

                }

            }.start();

        } else {
            RouteUtil.forwardHome(getApplication().getApplicationContext());

            getUIChangeLiveData().getFinishActivityEvent().call();
        }

    }


    @Override
    protected void showPermissionsError(String string) {
        super.showPermissionsError(string);

        MyToast.showShort(getApplication().getApplicationContext(), string);
        SimpleStyleDialog dialog = new SimpleStyleDialog(ActivityManager.getInstance().currentActivity(), "获取系统权限失败,是否去设置？");
        dialog.setPositiveButtonText("设置");
        dialog.setOnPositiveButtonClickListener(dialog1 -> {

            Intent mIntent = new Intent();
            mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (Build.VERSION.SDK_INT >= 9) {
                mIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                mIntent.setData(Uri.fromParts("package", getApplication().getPackageName(), null));
            } else if (Build.VERSION.SDK_INT <= 8) {
                mIntent.setAction(Intent.ACTION_VIEW);
                mIntent.setClassName("com.android.settings", "com.android.setting.InstalledAppDetails");
                mIntent.putExtra("com.android.settings.ApplicationPkgName", getApplication().getPackageName());
            }
            getApplication().startActivity(mIntent);

            getUIChangeLiveData().getFinishActivityEvent().call();

        });
        dialog.setCancelButtonText("取消");
        dialog.setOnCancelButtonClickListener(dialog12 -> {

        });
        dialog.show();

    }

}
